package com.atguigu.flink03;

import com.atguigu.beans.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * @author Felix
 * @date 2024/2/20
 * 该案例演示了Keyby的使用
 * 从指定的网络端口号获取水位传感器采集的信息，并相同的传感器水位值求和
 */
public class Flink11_Trans_KeyBy {
    public static void main(String[] args) throws Exception {
        //TODO 1.指定流处理环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(new Configuration());
        //TODO 2.从指定的网络端口读取水位数据  ws1,1,10
        DataStreamSource<String> socketDS = env.socketTextStream("hadoop102", 8888);
        //TODO 3.对读取的数据类型进行转换   String->WaterSensor
        SingleOutputStreamOperator<WaterSensor> wsDS = socketDS.map(
                new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String lineStr) throws Exception {
                        String[] strArr = lineStr.split(",");
                        return new WaterSensor(strArr[0], Long.parseLong(strArr[1]), Integer.parseInt(strArr[2]));
                    }
                }
        );
        //TODO 4.按照传感器id进行分组
        KeyedStream<WaterSensor, String> keyedDS = wsDS.keyBy(WaterSensor::getId);

        //TODO 5.求和
        SingleOutputStreamOperator<WaterSensor> sumDS = keyedDS.sum("vc");
        //TODO 6.打印
        sumDS.print();
        //TODO 7.提交作业
        env.execute();
    }
}
